<?php
/*
Plugin Name: ShortCodes
Description: Gestisce un set di ShortCodes
Plugin URI:  http://www.SyriusWeb.com/
Version:     1.1
Author:      SyriusWeb
Author URI:  http://www.SyriusWeb.com/
*/

/*
USAGE:
View readme
*/


define('SHORTCODES_DOMAIN','shortcodes');

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');


add_action('admin_init', 'sy_init_styles');
add_action('init', 'sy_init_styles');
function sy_init_styles() {		
	wp_register_style('shortcodes_css', plugins_url('/css/shortcodes.css',__FILE__ ));
	wp_enqueue_style('shortcodes_css');

	wp_register_style('visualize_css', plugins_url('/css/visualize.css',__FILE__ ));
	wp_enqueue_style('visualize_css');
	
	wp_register_style('visualize-dark_css', plugins_url('/css/visualize-dark.css',__FILE__ ));
	wp_enqueue_style('visualize-dark_css');
	
	//wp_register_style('visualize-light_css', plugins_url('/css/visualize-light.css',__FILE__ ));
	//wp_enqueue_style('visualize-light_css');
}

	
add_action( 'admin_init','sy_shortcodes_init_js');
add_action( 'init','sy_shortcodes_init_js');	
function sy_shortcodes_init_js() {

    wp_enqueue_script( 'jquery', '../wp-includes/js/jquery/jquery.js', false, '1.8.3');

	wp_register_script('init_js', plugins_url('/js/init.js',__FILE__ ));	
	wp_enqueue_script('init_js');
    
    wp_register_script('sparkline_js', plugins_url('/js/jquery.sparkline.min.js',__FILE__ ));	
	wp_enqueue_script('sparkline_js');
	
	wp_register_script('excanvas_js', plugins_url('/js/excanvas.compiled.js',__FILE__ ));	
	wp_enqueue_script('excanvas_js');
	
	wp_register_script('visualize_js', plugins_url('/js/visualize.jQuery.js',__FILE__ ));	
	wp_enqueue_script('visualize_js');

}





// DEFINE SHORTCODES


/*
*text* : 						visualizza ogni riga del loop in un <p></p>
*unordered* : 					visualizza ogni riga del loop in un <li></li> (dentro un <ul>)
*ordered* : 					visualizza ogni riga del loop in un <li></li> (dentro un <ol>)
*table* : 						visualizza ogni riga del loop come una riga di una tabella
*pie*, *bar*, *line* : 			come table, ma poi con classe idonea da essere catturata dal jquery
*sparkline* : 					inserisce ogni riga come <span class="sparklabel">PRIMO VALORE</span><span class="inlinesparkline"> e </span>
*sparkbar* : 					inserisce i campi in <span class="sparklabel">PRIMO VALORE</span><span class="inlinebar"> e </span>
*/



// [loop post_type="post" taxonomy="tag" term="scuola" mode="text|table|bar|pie|line|mixed"] content [/loop]

// Codice!Titolo!!fascicoli_code|aaaa||

add_shortcode( 'loop', 'loop_func' );
function loop_func( $atts, $content = null ) {
	$string = '';	
	
	extract( shortcode_atts( array(
		'post_type' => 'post',
		'taxonomy' => 'category',
		'term' => '',
		'mode' => 'text',
	), $atts ) );	
	
	// Args
	$args = array(
		'post_type' => $post_type,	
		'post_status' => 'publish'
	);
	
	if ($taxonomy == "tag") {
		$args['tag'] = $term;
	} else if ($taxonomy != "") {
		$args['tax_query'] = array(
			array(
				'taxonomy' => $taxonomy,
				'field' => 'slug',
				'terms' => $term
			)
		);
	}
	
	
	
		
	// Query
	global $query;
	$query = new WP_Query( $args );		
	
	$preloop = '';
	$prerow = '';
	$postrow = '';	
	$postloop = '';	
	
	list($dummy, $dummy2, $content) = explode("\n",trim($content), 3);
    list($th, $cell_temp) = explode('!!', $dummy2, 2); 
	list($cell, $cell_trash) = explode('||', $cell_temp, 2);               
        
	$th = str_replace('!', '</th><th>', $th);
	$td = str_replace('|', '</td><td>', $cell);
        
	$fields = explode('|' ,$cell);
	
	if ($mode == "text") {		
		$prerow = '<p>';
		$postrow = '</p>';		
	} else if ($mode == "unordered") {	
		$preloop = '<ul>';
		$prerow = '<li>';
		$postrow = '</li>';
		$postloop = '</ul>';
	} else if ($mode == "ordered") {
		$preloop = '<ol>';
		$prerow = '<li>';
		$postrow = '</li>';
		$postloop = '</ol>';
	} else if ( $mode == "table" || $mode == "pie" || $mode == "bar" || $mode == "line" || $mode == "area"  ) {
        
        $preloop = '<table class="'.$mode.'">
			<caption>Caption</caption>
			<thead>
				<tr>
					<td></td>
					<th>'.$th.'</th>
				</tr>
			</thead>
			<tbody>';
		$prerow = '<tr>
			<th>Title</th>
			<td>'.$td.'</td>';
		$postrow = '</td></tr>';
		$postloop = '</tbody></table>';		
			
		
	} else if ( $mode == "sparkline" || $mode == "sparkbar" ) {		
		
		
		
	}
	
	
	
	$sparkclass = "";
	
	if ($query->have_posts()) {
		$string .= $preloop;
		// Loop
		while ( $query->have_posts() ) {		
			$query->the_post();	
			
			if ($mode == "sparkline") {
				// al primo valore assegna "sparklabel" e agli altri assegna "inlinesparkline"
				if ($sparkclass == "") {
					$sparkclass = "sparklabel";
				} else {
					$sparkclass = "inlinesparkline";
				}
			} else if ($mode == "sparkbar") {
				// al primo valore assegna "sparklabel" e agli altri assegna "inlinebar"
				if ($sparkclass == "") {
					$sparkclass = "sparklabel";
				} else {
					$sparkclass = "inlinebar";
				}
			
			} else if ($mode == "table" || $mode == "pie" || $mode == "bar" || $mode == "line" ) {
                //$content = str_replace('|','</td><td>', $content);
            }
            $prerow_temp = $prerow;            
            
            foreach ($fields as $f) {
            	$meta_value = get_post_meta( $query->post->ID, $f );            	
            	//bisogna controllare che sia un array
            	
            	$prerow_temp = str_replace($f, $meta_value[0], $prerow_temp);
            	
            }            
            
            $prerow_temp = str_replace('Title', $query->post->post_title, $prerow_temp);
            
			$string .= $prerow_temp . do_shortcode($content) . $postrow;
			
		}
		$string .= $postloop;
		
	}	
	
	wp_reset_query();
	
	// Questa è una pezza da controllare in seguito
	// non so perchè, ma stampa a video il contenuto del loop sempre tra <p> e </p>
	if ($mode != "text") {
		$string = str_replace("<p>", "", $string);
		$string = str_replace("</p>", "", $string);
	}	

	
	return $string;	
	 
}






//[loop-field id="xxx" custom-field="voce" mode="table"] 
//Quantita!Prodotto!Prezzo!Totale!!quantità|descrizione|prezzo||
//[formula name="Totale" operation="quantità*prezzo"]
//[/loop-field]




add_shortcode( 'loop_field', 'loop_field_func' );
function loop_field_func( $atts, $content = null ) {
	
	$string = '';	
	$preloop = '';
	$prerow = '';
	$postrow = '';	
	$postloop = '';	
	
	
	extract( shortcode_atts( array(
		'id' => '',
		'custom_field' => '',
		'mode' => 'text',
	), $atts ) );	
	
	
	
	if ($id != "") {
	
		$post = get_post( $id );
		$meta_values = get_post_meta( $post->ID, $custom_field );		
		
		if (is_array($meta_values)) {	
	
			list($dummy, $dummy2, $content) = explode("\n",trim($content), 3);
		    list($th, $cell_temp) = explode('!!', $dummy2, 2); 
			list($cell, $cell_trash) = explode('||', $cell_temp, 2);               
		        
			$th = str_replace('!', '</th><th>', $th);
			$td = str_replace('|', '</td><td>', $cell);
		        
			$fields = explode('|' ,$cell);
			
			if ($mode == "text") {		
				$prerow = '<p>';
				$postrow = '</p>';		
			} else if ($mode == "unordered") {	
				$preloop = '<ul>';
				$prerow = '<li>';
				$postrow = '</li>';
				$postloop = '</ul>';
			} else if ($mode == "ordered") {
				$preloop = '<ol>';
				$prerow = '<li>';
				$postrow = '</li>';
				$postloop = '</ol>';
			} else if ( $mode == "table" || $mode == "pie" || $mode == "bar" || $mode == "line" || $mode == "area"  ) {
		        
		        $preloop = '<table class="'.$mode.'">
					<caption>Caption</caption>
					<thead>
						<tr>
							<td></td>
							<th>'.$th.'</th>
						</tr>
					</thead>
					<tbody>';
				$prerow = '<tr>
					<th>Title</th>
					<td>'.$td.'</td>';
				$postrow = '</td></tr>';
				$postloop = '</tbody></table>';				
			} 
			
			$string .= $preloop;
			
			// Loop
			foreach ($meta_values as $k=>$meta) {
				if (is_array($meta)) {	
					foreach ($meta as $key=>$mv) {					
						$prerow_temp = $prerow;			            
			            $prerow_temp = str_replace($key, $mv, $prerow_temp);			            
			            $prerow_temp = str_replace('Title', $key, $prerow_temp);			            
						$string .= $prerow_temp . do_shortcode($content) . $postrow;
					}	
				} else {					
					$prerow_temp = $prerow;			            
		            $prerow_temp = str_replace($k, $meta, $prerow_temp);		            
		            $prerow_temp = str_replace('Title', $k, $prerow_temp);		            
					$string .= $prerow_temp . do_shortcode($content) . $postrow;					
				}				
			}
			
			$string .= $postloop;	
		
			// Questa è una pezza da controllare in seguito
			// non so perchè, ma stampa a video il contenuto del loop sempre tra <p> e </p>
			if ($mode != "text") {
				$string = str_replace("<p>", "", $string);
				$string = str_replace("</p>", "", $string);
			}	
		
			
			return $string;	
		
		}
	}	 
}




// [loop_comment post_id="0" mode="text|table|bar|pie|line|mixed"] content [/loop]
add_shortcode( 'loop_comment', 'loop_comment_func' );
function loop_comment_func( $atts, $content = null ) {
	$string = '';
	
	extract( shortcode_atts( array(
		'post_id' => '',
		'mode' => 'text'
	), $atts ) );
	
	
	// Args
	$args = array(
		'p' => $post_id,
		'post_status' => 'publish'
	);	
	
	
	//var_dump($post_id);
	
	// Query
	$query = new WP_Query( $args );	
		
	//var_dump($query);
	
	if ($post_id) {		
		
		// Loop
		if ( $query->have_posts() ) {		
			$query->the_post();
			
			$args_com = array(				
				'status' => 'approve'
			);
			
			$comments = get_comments( $args_com );
			
			$string .= do_shortcode($content);
			
			if (count($comments) > 0) {
				$string .= '<ul>';
				foreach($comments as $comment) {
					$string .= '<li>' . $comment->comment_author . '<br />' . $comment->comment_content . '</li>';
				}
				$string .= '</ul>';
			}							
		}	
		
		wp_reset_query();
	}
	
	// Questa Ã¨ una pezza da controllare in seguito
	// non so perchÃ¨, ma stampa a video il contenuto del loop sempre tra <p> e </p>
	if ($mode != "text") {
		$string = str_replace("<p>", "", $string);
		$string = str_replace("</p>", "", $string);
	}
	
	return $string;		 
}


// [field name="post_title"; name="comment_count"]
add_shortcode( 'field', 'field_func' );
function field_func( $atts, $content = null ) {
	global $post;
	global $query;	
	
	/*
	* operations : sum, max, min, av	
	*/
	
	
	
	extract( shortcode_atts( array(
		'name' => 'post_title',
		'operation' => '',
		'as' => ''
	), $atts ) );	
	
	
	if ($operation != "") {	
		
		$op = 0;
		$oparray = array();
		
		if ($query->have_posts()) {
			$string .= $preloop;
			// Loop
			while ( $query->have_posts() ) {		
				$query->the_post();	
				
				//@TODO Quali altri operazioni? bisogna controllare i tipi?
				
				if ($operation == "sum") {
					$op = $op + $query->post->$name;
				} else if ($operation == "av") {
					$op = $op + $query->post->$name;
					$op = $op / $query->found_posts;
				} else if ($operation == "max" || $operation == "min") {
					$oparray[] = $query->post->$name;
				}		
			}			
		}
		
		if ($operation == "max") {
			$op = max($oparray);
		} else if ( $operation == "min") {
			$op = min($oparray);
		}
		
		return $op." ".$as;
		
	} else {
		if ($post->$name) {
			$string = $post->$name;	
		} else {
			return "not found";
		}
	}	
	
	return $string;	
}


// [if name="post_title" is="equal" value="0"] cond [/if]
add_shortcode( 'if', 'if_func' );
function if_func( $atts, $content = null ) {	
	
	global $post;
	global $if_cond;
	
	extract( shortcode_atts( array(
		'name' => '',
		'is' => '',
		'value' => '',
        'value2' => ''
	), $atts ) );
	
	$if_cond = false;
	
	
	/*
	* equal : uguale						->	done
	* major : maggiore (tra numeri)			->	done
	* minor : minore (tra numeri)			->	done
	* before : minore (tra date)			->	done
	* after  : maggiore (tra date)			->	done
	* between : campreso tra due date		->	manca un parametro
	* in : compreso tra 2 numeri			->	manca un parametro
	* like : %like% tra stringhe			->	done (verificare l'ordine)
	*/

	
	if ( $is == "major" || $is == "minor" || $is == "in") {			
		$post->$name = intval ($post->$name);
		$value = intval ($value);
		$value2 = intval ($value2);		
	} 
	
	
	
	
	if ($name && $is && $value) {
		
		if ($post->$name) {		
			if ( ($is == "equal") && ($post->$name == $value)) {			
				$if_cond = true;			
			} else if ( ($is == "major") && ($post->$name > $value) && ( is_int($post->$name) && is_int($value) ) ) {			
				$if_cond = true;
			} else if ( ($is == "minor") && ($post->$name < $value) && ( is_int($post->$name) && is_int($value) ) ) {			
				$if_cond = true;
			} else if ( ($is == "after") && (strtotime($post->$name) > strtotime($value)) && ( strtotime($post->$name) === true && strtotime($value) === true ) ) {			
				$if_cond = true;
			} else if ( ($is == "before") && (strtotime($post->$name) < strtotime($value)) && ( strtotime($post->$name) === true && strtotime($value) === true ) ) {			
				$if_cond = true;
			} else if ( ($is == "like") && (strpos($post->$name, $value) === true) && ($post->$name && $value) ) {			
				$if_cond = true;			
			} else if ( ($is == "between") && (strtotime($post->$name) >= strtotime($value)) && strtotime($post->$name) <= strtotime($value2) && ( strtotime($post->$name) === true && strtotime($value) === true && strtotime($value2) === true ) ) {	
				$if_cond = true;
			} else if ( ($is == "in") && ($post->$name >= $value) && ($post->$name <= $value2) && ( is_int($post->$name) && is_int($value) && is_int($value2) ) ) {	
				$if_cond = true;
			}
		}
	}	
	
	if ($if_cond) {
		return do_shortcode($content);
	}	
}

// [else] questo se non Ã¨ vero l'ultimo if [/else]
add_shortcode( 'else', 'else_func' );
function else_func( $atts, $content = null ) {
	global $if_cond;
	
	if (!$if_cond) {
		return do_shortcode($content);
	}	
}



// [cond name="comment_count" range="5,10" class="red,yellow,green"] cond [/cond]
add_shortcode( 'cond', 'cond_func' );
function cond_func( $atts, $content = null ) {
	global $post;
	
	extract( shortcode_atts( array(
		'name' => '',
		'range' => '',
		'class' => ''
	), $atts ) );
	
	$rangeArray = array();
	$classArray = array();
	
	$rangeArray = explode(',', $range);
	$classArray = explode(',', $class);
	
	///////////////// vecchio codice
	/* 
	if ($name && count($rangeArray) == 2 && count($classArray) == 3) {
		if ($name < $rangeArray[0]) {
			$class = $classArray[0];
		} else if ( ($rangeArray[0] <= $name) && ($name <= $rangeArray[1]) ) {
			$class = $classArray[1];
		} else if ($name > $rangeArray[1]) {
			$class = $classArray[2];
		}
	}
	*/	
	
	$count = count($rangeArray);
	if ($name && $post->$name && count($classArray) == count($rangeArray)+1) {
	   for($i=0; $i < $count; $i++) { 
	        if ( ($rangeArray[$i] < $post->$name) && ($post->$name <= $rangeArray[$i+1]) ) {
	        	$class = $classArray[$i];
	        } else {
	        	$class = $classArray[$i]+1;
	        }
		}
	} else {
		return '<span>'.do_shortcode($content).'</span>';
	}	
	
	return '<span class="'.$class.'">'.do_shortcode($content).'</span>';
	
}


// [head_page] text [/head_page]
add_shortcode( 'head_page', 'head_page_func' );
function head_page_func( $atts, $content = null ) {	
	//@TODO definire formattazione
	return do_shortcode($content);		
}


// [foot_page] text [/foot_page]
add_shortcode( 'foot_page', 'foot_page_func' );
function foot_page_func( $atts, $content = null ) {	
	//@TODO definire formattazione
	return do_shortcode($content);		
}


// [break_page]
add_shortcode( 'break_page', 'break_page_func' );
function break_page_func( $atts, $content = null ) {	
	return "<!--more-->";			
}